$file1 = $ARGV[0];
chomp($file1);
$file2 = $ARGV[1];
chomp($file2);
open TFAM1,"<$file1.tfam" or die "arg1 $file1.tfam not found\n";
open TFAM2,"<$file2.tfam" or die "arg1 $file2.tfam not found\n";
open TPED1,"<$file1.tped" or die "arg1 $file1.tped not found\n";
open TPED2,"<$file2.tped" or die "arg1 $file2.tped not found\n";

$wrfile = $ARGV[2];
chomp($wrfile);
open(WRTFAM,">$wrfile.tfam");
open(WRTPED,">$wrfile.tped");
while($line = <TFAM1>)
{
	print WRTFAM $line;
}
while($line = <TFAM2>)
{
        print WRTFAM $line;
}
while($line=<TPED1>)
{
	chomp($line);
	@array = split(" ",$line);
	$l1 = @array;
	$hash{$array[1]} = 1;
	$hash1{$array[1]} = $line;
}
while($line=<TPED2>)
{
        chomp($line);
        @array = split(" ",$line);
	$l2 = @array;
	if(exists($hash{$array[1]}))
	{
		$hash{$array[1]} = 0;
	}
	else
	{
		$hash{$array[1]} = 2;
	}
	$hash2{$array[1]} = $line;

}
$l1 = $l1-4;
$l2 = $l2-4;
for($i=0;$i<$l1;$i++)
{
	$arr1[$i] = "0";
}
for($i=0;$i<$l2;$i++)
{
        $arr2[$i] = "0";
}
$miss1 = join(" ",@arr1);
$miss2 = join(" ",@arr2);
while(($key,$value) = each %hash)
{
	#print $key."\t".$value."\n";
	@array = ();
	@array1 = ();
	if($value == 0)
	{
		@array = split(" ",$hash1{$key});
		@array1= split(" ",$hash2{$key});
		shift(@array1);
		shift(@array1);
		shift(@array1);
		shift(@array1);
		$li1 = join(" ",@array);
		$li2 = join(" ",@array1);
		print WRTPED $li1." ".$li2."\n"; 
	}
	elsif($value == 1)
	{
		print WRTPED $hash1{$key}." ".$miss2."\n";

	}
	elsif($value == 2)
	{
		@array1= split(" ",$hash2{$key});
		$v1 = shift(@array1);
                $v2 = shift(@array1);
                $v3 = shift(@array1);
                $v4 = shift(@array1);
		print WRTPED "$v1 $v2 $v3 $v4 ".$miss1." ".join(" ",@array1)."\n";
	}
	else
	{
		die "something wrong with the $key\t$value\n";	
	}
}

